import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import {
  DValidateRules,
  DialogService,
  FormLayout,
  TableWidthConfig,
} from 'ng-devui';
import { SaleOrder } from 'src/app/@core/data/sale';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { SelectCustomerComponent } from 'src/app/@shared/components/select-customer/select-customer.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { SetDeliveryDateComponent } from '../set-delivery-date/set-delivery-date.component';
import * as XLSX from 'xlsx';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { environment } from 'src/environments/environment';
import { SelectSalesOrderComponent } from '../add-sales-order/select-sales-order/select-sales-order.component';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';

@Component({
  selector: 'app-edit-sales-order',
  templateUrl: './edit-sales-order.component.html',
  styleUrls: ['./edit-sales-order.component.scss'],
})
export class EditSalesOrderComponent {
  Math = Math;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  saleOrder: SaleOrder = {
    saleOrderId: 0, // 销售订单ID
    quotationNum: '', // 报价单号
    saleOrderNum: '', // 销售订单号
    orderDate: null, // 订单日期
    customerOrderNum: '', // 客户订单号
    customerName: '', // 客户名称
    deliveryDate: null, // 交货日期
    status: '未开始审核', // 是否审核
    isClosed: false, // 是否关闭
    partTotalQuantity: 0, // 零件总数量
    partShippedQuantity: 0, // 已发货数量
    partUnshippedQuantity: 0, // 未发货数量
    advancePaymentAmount: 0, // 预付款金额
    creationDate: null, // 创建日期
    creator: '', // 创建者
    orderType: '', // 订单类型
    company: '', // 公司
    customerShortName: '', // 客户简称
    customerContact: '', // 客户联系人
    contactInfo: '', // 联系信息
    salesman: '', // 销售员
    department: '', // 部门
    settlementCurrency: '', // 结算货币
    settlementMethod: '', // 结算方式
    paymentTerm: '', // 付款条件
    deliveryAddress: '', // 交货地址
    remark: '', // 备注
    totalQuantity: 0, // 总数量
    totalAmountWithTax: 0, // 含税总金额
    totalTaxAmount: 0, // 总税额
    totalDiscountAmountWithTax: 0, // 折扣后含税总金额
    totalDiscountTaxAmount: 0, // 折扣后总税额
    files: [], // 文件列表
    fileRemarks: [], // 文件备注
    saleOrderParts: [
      {
        saleOrderPartId: 0, // 零件ID
        saleOrderNum: '', // 销售订单号
        saleOrderPartPartId: 0,
        partNum: '', // 零件编号
        image: '', // 图片
        attachment: '', // 附件
        partName: '', // 零件名称
        partType: '', // 零件类型
        description: '', // 描述
        plannedShipmentDate: null, // 计划发货日期
        salesQuantity: 0, // 销售数量
        realTimeInventory: 0, // 实时库存
        sourceQuotationNum: '', // 来源报价单号
        quantity: 0, // 数量
        partUOM: '', // 单位
        priceWithTax: 0, // 含税价格
        priceWithoutTax: 0, // 不含税价格
        taxRate: 0, // 税率
        discount: 1, // 折扣
        discountPriceWithTax: 0, // 折扣后含税价格
        amountWithTax: 0, // 含税金额
        amountWithoutTax: 0, // 不含税金额
        taxAmount: 0, // 税额
        discountAmountWithTax: 0, // 折扣后含税金额
        discountAmountWithoutTax: 0, // 折扣后不含税金额
        discountTaxAmount: 0, // 折扣后税额
        partRemark: '', // 零件备注
        saleOrderId: 0, // 销售订单ID,
        quotationItemId: 0,
        produceQuantity: 0,
        soldQuantity: 0,
        unSoldQuantity: 0,
      },
    ],
    customerContactID: undefined,
    customerID: undefined,
  };
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '200px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '规格型号',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '计划发货日期',
      width: '200px',
    },
    {
      field: '数量',
      width: '170px',
    },
    {
      field: '单位',
      width: '150px',
    },
    {
      field: '单价(含税)',
      width: '170px',
    },
    {
      field: '单价（不含税）',
      width: '150px',
    },
    {
      field: '税率（%）',
      width: '170px',
    },
    {
      field: '折扣（%）',
      width: '150px',
    },
    {
      field: '折扣单价（含税）',
      width: '150px',
    },
    {
      field: '含税金额',
      width: '150px',
    },
    {
      field: '不含税金额',
      width: '150px',
    },
    {
      field: '税额',
      width: '150px',
    },
    {
      field: '折扣不含税金额',
      width: '150px',
    },
    {
      field: '折扣含税金额',
      width: '150px',
    },
    {
      field: '折扣税额',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
    {
      field: '来源报价单号',
      width: '150px',
    },
  ];
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '计划发货日期',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价(含税)',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价（不含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税率（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣单价（含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '来源报价单号',
        fieldType: 'text',
      },
    ],
  };
  saleOrderRules: { [key: string]: DValidateRules } = {
    saleOrderNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*订单号不能为空' },
        { minlength: 2, message: '*订单号长度至少为2' },
        { maxlength: 40, message: '*订单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*订单号不能包含空格' },
      ],
    },
    customerName: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*客户不能为空' }],
    },
    orderDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*单据日期不能为空' }],
    },
    partNum: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*物料不能为空' }],
    },
    plannedShipmentDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*发货时间不能为空' }],
    },
    priceWithTax: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*物料单价不能为空' }],
    },
    quantity: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*数量不能为空' }],
    },
    salesman: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*业务员不能为空' }],
    },
  };
  customerLinkMan: any = [];
  msgs: Array<Object> = [];
  customerContact: any = [];
  currencyOptions: any = [];
  settlementMethodOptions: any = [];
  defaultDate: any = null;
  defaultDiscount: any;
  constructor(
    private DialogService: DialogService,
    private UserService: UserService,
    private CustomerService: CustomerService,
    private SalesService: SalesService,
    private MaterialService: MaterialService,
    private router: Router,
    private route: ActivatedRoute,
    private StorehouseService: StorehouseService,
    private ReviewRolesService:ReviewRolesService
  ) {}
  ngOnInit(): void {
    this.route.params.subscribe((params: any) => {
      if (params.id) {
        this.SalesService.GetSaleOrderById(params.id).subscribe((data: any) => {
          this.saleOrder = data;
          this.saleOrder.orderDate = new Date(data.orderDate);
          this.saleOrder.deliveryDate = new Date(data.deliveryDate);
          this.CustomerService.GetCustomerById(data.customerID).subscribe(
            (data: any) => {
              this.customerLinkMan = data.customerContacts;
            }
          );
          this.customerContact = {
            customerContactId: data.customerContactID,
            customerContactName: data.customerContact,
          };
          this.saleOrder.saleOrderParts.forEach((item) => {
            item.plannedShipmentDate = new Date(item.plannedShipmentDate);
            this.calculateAmount(item);
          });
          this.defaultDate = this.saleOrder.deliveryDate;
          this.calculateTotal();
        });
      }
    });
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((data: any) => {
      this.currencyOptions = data.items;
    });
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe(
      (data: any) => {
        this.settlementMethodOptions = data.items;
      }
    );
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.saleOrder.creator = JSON.parse(userinfoString).username;
    }
  }
  addRow() {
    this.saleOrder.saleOrderParts.push({
      saleOrderPartId: 0,
      saleOrderNum: '',
      saleOrderPartPartId: 0,
      partNum: '',
      image: '',
      attachment: '',
      partName: '',
      partType: '',
      description: '',
      plannedShipmentDate: this.defaultDate,
      salesQuantity: 0,
      realTimeInventory: 0,
      sourceQuotationNum: '',
      quantity: 0,
      partUOM: '',
      priceWithTax: 0,
      priceWithoutTax: 0,
      taxRate: 0,
      discount: 1,
      discountPriceWithTax: 0,
      amountWithTax: 0,
      amountWithoutTax: 0,
      taxAmount: 0,
      discountAmountWithTax: 0,
      discountAmountWithoutTax: 0,
      discountTaxAmount: 0,
      partRemark: '',
      saleOrderId: 0,
      quotationItemId: 0,
      produceQuantity: 0,
      soldQuantity: 0,
      unSoldQuantity: 0,
    });
  } //添加行
  deleteRow(index: number) {
    this.saleOrder.saleOrderParts.splice(index, 1);
    this.calculateTotal();
    if (this.saleOrder.saleOrderParts.length == 0) {
      this.addRow();
    }
  } //删除行
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
    this.calculateTotal();
  } //税率改变
  quantityChange(rowitem: any) {
    this.calculateAmount(rowitem);
    this.calculateTotal();
  } //数量改变
  priceWithTaxChange(rowitem: any) {
    this.calculateAmount(rowitem);
    this.calculateTotal();
  } //含税单价改变
  discountChange(rowitem: any, value: number) {
    rowitem.discount = value / 100;
    this.calculateAmount(rowitem);
    this.calculateTotal();
  } //折扣改变
  calculateAmount(item: any): void {
    item.amountWithTax = +(item.priceWithTax * item.quantity).toFixed(4);
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.taxAmount = +(
      (item.priceWithTax - item.priceWithoutTax) *
      item.quantity
    ).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    item.discountedPriceWithTax = +(item.priceWithTax * item.discount).toFixed(
      4
    );
    item.discountAmountWithTax = +(item.amountWithTax * item.discount).toFixed(
      4
    );
    item.discountTaxAmount = +(item.taxAmount * item.discount).toFixed(4);
    item.discountAmountWithoutTax = +(
      item.discountAmountWithTax - item.discountTaxAmount
    ).toFixed(4);
  }
  calculateTotal() {
    this.saleOrder.totalQuantity = this.saleOrder.saleOrderParts.reduce(
      (prev, cur) => prev + cur.quantity,
      0
    );
    this.saleOrder.totalAmountWithTax = this.saleOrder.saleOrderParts.reduce(
      (prev, cur) => prev + cur.amountWithTax,
      0
    );
    this.saleOrder.totalTaxAmount = +this.saleOrder.saleOrderParts
      .reduce((prev, cur) => prev + cur.taxAmount, 0)
      .toFixed(4);
    this.saleOrder.totalDiscountAmountWithTax =
      this.saleOrder.saleOrderParts.reduce(
        (prev, cur) => prev + cur.discountAmountWithTax,
        0
      );
    this.saleOrder.totalDiscountTaxAmount =
      this.saleOrder.saleOrderParts.reduce(
        (prev, cur) => prev + cur.discountTaxAmount,
        0
      );
  } //计算总金额
  submit($event: any) {
    this.saleOrder.creationDate = new Date();
    this.saleOrder.saleOrderParts.forEach((item: any) => {
      item.saleOrderNum = this.saleOrder.saleOrderNum;
    });
    if (this.validateSalesQuotation(this.saleOrder)) {
      this.SalesService.UpdateSaleOrder(
        this.saleOrder.saleOrderId,
        this.saleOrder
      ).subscribe(
        (data: any) => {
          if (this.isStartApproval) {
            this.ReviewRolesService.StartApprovalFlow('销售订单审核流配置',[this.saleOrder.saleOrderNum]).subscribe((data:any)=>{
              this.showToast('success','成功','更新成功')
              setTimeout(() => {
                this.router.navigate(['/pages/sales-master/sales-order'])
              }, 1000)
            },error=>{
              this.showToast('error','失败','单据更新成功，流程启动失败')
              setTimeout(() => {
                this.router.navigate(['/pages/sales-master/sales-order'])
              }, 1000)
            })
          } else {
            this.showToast('success', '成功', '更新成功');
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-order']);
            }, 1000);
          }
        },
        (error) => {
          if (error.status == 404) {
            this.showToast('error', '失败', '服务器连接失败');
          } else {
            this.showToast('error', '失败', error.error);
          }
        }
      );
    }
  } //提交
  isStartApproval: boolean = false;
  isStartApprovalChange() {
    this.isStartApproval = true;
  }
  selectCustomer(dialogtype?: string, reset?: boolean) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择客户',
      content: SelectCustomerComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.saleOrder.customerName =
              results.modalContentInstance.selectData.chineseName;
            this.saleOrder.customerID =
              results.modalContentInstance.selectData.customerId;
            this.saleOrder.customerShortName =
              results.modalContentInstance.selectData.customerAbbreviation;
            this.customerLinkMan =
              results.modalContentInstance.selectData.customerContacts;
            this.saleOrder.settlementCurrency =
              results.modalContentInstance.selectData.customerCurrencyName;
            this.saleOrder.settlementMethod =
              results.modalContentInstance.selectData.customerSettlementMethodName;
            this.saleOrder.paymentTerm =
              results.modalContentInstance.selectData.customerCollectionPeriodName;
            this.saleOrder.deliveryAddress =
              results.modalContentInstance.selectData.invoiceAddress;
            this.defaultDiscount =
              results.modalContentInstance.selectData.customerDiscountDiscount;
            if (
              results.modalContentInstance.selectData.customerContacts.length >
              0
            ) {
              this.saleOrder.customerContact =
                results.modalContentInstance.selectData.customerContacts[0].customerContactName;
              this.saleOrder.contactInfo =
                results.modalContentInstance.selectData.customerContacts[0].phone;
              this.saleOrder.customerContactID =
                results.modalContentInstance.selectData.customerContacts[0].customerContactId;
              this.customerContact = {
                customerContactId:
                  results.modalContentInstance.selectData.customerContacts[0]
                    .customerContactId,
                customerContactName:
                  results.modalContentInstance.selectData.customerContacts[0]
                    .customerContactName,
              };
            }
            if (reset) {
              this.saleOrder.saleOrderParts = [
                {
                  saleOrderPartId: 0,
                  saleOrderPartPartId: 0,
                  saleOrderNum: '',
                  quotationItemId: 0,
                  partNum: '',
                  image: '',
                  attachment: '',
                  partName: '',
                  partType: '',
                  description: '',
                  plannedShipmentDate: null,
                  salesQuantity: 0,
                  realTimeInventory: 0,
                  sourceQuotationNum: '',
                  quantity: 0,
                  partUOM: '',
                  priceWithTax: 0,
                  priceWithoutTax: 0,
                  taxRate: 0,
                  discount: 0,
                  discountPriceWithTax: 0,
                  amountWithTax: 0,
                  amountWithoutTax: 0,
                  taxAmount: 0,
                  discountAmountWithTax: 0,
                  discountAmountWithoutTax: 0,
                  discountTaxAmount: 0,
                  partRemark: '',
                  saleOrderId: 0,
                  produceQuantity: 0,
                  soldQuantity: 0,
                  unSoldQuantity: 0,
                },
              ];
              this.calculateAmount(this.saleOrder.saleOrderParts[0]);
            }
            this.UserService.GetUserById(
              results.modalContentInstance.selectData.salesmanId
            ).subscribe((data: any) => {
              this.saleOrder.salesman = data.name;
              this.UserService.GetDepartmentById(data.departmentId).subscribe(
                (data: any) => {
                  this.saleOrder.department = data.name;
                }
              );
            });
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectCustomerBefore(dialogtype: string) {
    if (
      this.saleOrder.saleOrderParts[0].partNum &&
      this.saleOrder.customerName
    ) {
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: true,
        data: '',
        title: '',
        dialogtype: dialogtype,
        html: true,
        content:
          '<div style="color:#8a6d3b;font-size: 14px;">确定切换客户，这将会使您构建的物料行数据重置！</div>',
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.selectCustomer(null, true);
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    } else {
      this.selectCustomer();
    }
  }
  selectUser(dialogtype?: string) {
    if (this.saleOrder.customerName != '') {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: '',
        title: '选择业务员',
        content: SelectUserComponent,
        dialogtype: dialogtype,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.saleOrder.salesman =
                results.modalContentInstance.selectData.name;
              this.UserService.GetDepartmentById(
                results.modalContentInstance.selectData.departmentId
              ).subscribe((data: any) => {
                this.saleOrder.department = data.name;
              });
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    } else {
      this.showToast('error', '错误', '请先选择客户');
    }
  }
  slectLinkMan(event: any) {
    this.CustomerService.GetCustomerContactById(event).subscribe(
      (data: any) => {
        this.saleOrder.customerContact = data.customerContactName;
        this.saleOrder.contactInfo = data.phone;
      }
    );
  }
  selectMaterial(rowItem: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择物料',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.partNum = results.modalContentInstance.selectData.partNum;
            rowItem.saleOrderPartPartId =
              results.modalContentInstance.selectData.partId;
            rowItem.image = results.modalContentInstance.selectData.fileURL;
            rowItem.partName = results.modalContentInstance.selectData.partName;
            rowItem.partType = results.modalContentInstance.selectData.partType;
            rowItem.description =
              results.modalContentInstance.selectData.description;
            rowItem.partUOM = results.modalContentInstance.selectData.partUOM;
            rowItem.priceWithTax =
              results.modalContentInstance.selectData.salePrice;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  @ViewChild('fileInput') fileInput: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput.nativeElement.click();
  }
  onFileChange(event: any) {
    const file = event.target.files[0]; // 获取选中的文件
    if (file) {
      this.readExcel(file); // 调用readExcel方法并传递文件对象
      event.target.value = '';
    }
  }
  readExcel(file: any) {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      // 假设我们只处理第一个工作表
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      // 将工作表转换为JSON
      const json = XLSX.utils.sheet_to_json(worksheet);

      json.forEach((item, index) => {
        this.saleOrder.saleOrderParts[index].partNum = item['物料编号'];
        this.MaterialService.getParts(
          null,
          null,
          item['物料编号'],
          1,
          1
        ).subscribe((data: any) => {
          this.saleOrder.saleOrderParts[index].image = data.items[0].fileURL;
          this.saleOrder.saleOrderParts[index].partName =
            data.items[0].partName;
          this.saleOrder.saleOrderParts[index].partType =
            data.items[0].partType;
          this.saleOrder.saleOrderParts[index].description =
            data.items[0].description;
          this.saleOrder.saleOrderParts[index].partUOM = data.items[0].partUOM;
          this.saleOrder.saleOrderParts[index].priceWithTax =
            data.items[0].salePrice;
        });
        this.saleOrder.saleOrderParts[index].quantity = item['数量'];
        this.saleOrder.saleOrderParts[index].plannedShipmentDate = new Date(
          item['计划发货时间']
        );
        this.saleOrder.saleOrderParts[index].priceWithTax = item['单价'];
        this.saleOrder.saleOrderParts[index].taxRate = item['税率'];
        this.saleOrder.saleOrderParts[index].partRemark = item['备注'];
        this.calculateAmount(this.saleOrder.saleOrderParts[index]);
        this.calculateTotal();
      });
    };
    reader.readAsArrayBuffer(file);
  }
  writeExcel() {
    const headers = [
      '物料编号',
      '数量',
      '计划发货时间',
      '单价',
      '税率',
      '备注',
    ];
    const ws = XLSX.utils.aoa_to_sheet([headers]);
    const redFontStyle = { font: { color: { rgb: '#FF0000' } } };
    ws['A1'].s = redFontStyle;
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, '销售订单物料表.xlsx');
  }
  DeliveryDate($event) {
    this.defaultDate = $event;
    this.saleOrder.saleOrderParts.forEach((item) => {
      item.plannedShipmentDate = $event;
    });
  }
  setDeliveryDate(dialogtype?: string) {
    let data = {
      display: false,
    };
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: data,
      title: '选择计划发货日期',
      content: SetDeliveryDateComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.plannedShipmentDate) {
              this.saleOrder.saleOrderParts.forEach((item) => {
                item.plannedShipmentDate =
                  results.modalContentInstance.form.plannedShipmentDate;
                results.modalInstance.hide();
              });
            } else {
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cancel() {
    this.router.navigate(['/pages/sales-master/sales-order']);
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '销售附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: this.saleOrder.files,
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.saleOrder.files.push(results.modalContentInstance.urls);

            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  uploadSaleOrderPartsFromExcel(event: any) {
    const fileInput = event.target;
    const file = event.target.files[0];
    this.SalesService.GetSaleOrderPartsFromExcel(file).subscribe(
      (res: any) => {
        this.saleOrder.saleOrderParts = this.saleOrder.saleOrderParts
          .filter((item) => item.partNum !== '')
          .concat(res);
        this.saleOrder.saleOrderParts.map((item) => {
          this.calculateAmount(item);
        });
        this.showToast('success', '成功', '上传成功');
        this.calculateTotal();
        fileInput.value = '';
      },
      (error) => {
        // 如果发生错误也重置，确保用户可以重新尝试上传
        fileInput.value = '';
        this.showToast('error', '错误', error.error);
      }
    );
  }
  validateSalesQuotation(SaleOrder: SaleOrder): boolean {
    for (const [index, item] of SaleOrder.saleOrderParts.entries()) {
      if (!item.partNum) {
        this.showToast('error', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.quantity <= 0) {
        this.showToast('error', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }
      if (item.priceWithTax <= 0) {
        this.showToast('error', '错误', `第${index + 1}行单价(含税)必须大于0`);
        return false;
      }
      if (!item.plannedShipmentDate) {
        this.showToast('error', '错误', `第${index + 1}行计划发货日期不能为空`);
        return false;
      }
    }
    return true;
  } // 所有验证通过
  checkCustomerIDs(customerRows: any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].quotation.customerID;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every(
      (row: any) => row.quotation.customerID === firstCustomerID
    );
  }
  selectOrder(dialogtype?: string) {
    const quotationItemId = this.saleOrder.saleOrderParts.map(
      (part) => part.quotationItemId
    );
    const customerName = this.saleOrder.customerName || '';
    const results = this.DialogService.open({
      id: 'Add',
      width: '1250px',
      data: {
        quotationItemId: quotationItemId,
        customerName: customerName,
      },
      backdropCloseable: true,
      title: '选择报价单',
      content: SelectSalesOrderComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.filterRows) {
              if (
                this.checkCustomerIDs(results.modalContentInstance.filterRows)
              ) {
                if (results.modalContentInstance.filterRows.length > 1) {
                  this.CustomerService.GetCustomerById(
                    results.modalContentInstance.filterRows[0].quotation
                      .customerID
                  ).subscribe((data: any) => {
                    console.log(data);
                    this.saleOrder.customerID = data.customerId;
                    this.customerLinkMan = data.customerContacts;
                    this.saleOrder.customerName = data.chineseName;
                    this.saleOrder.customerShortName =
                      data.customerAbbreviation;
                    this.saleOrder.settlementCurrency =
                      data.customerCurrencyName;
                    this.saleOrder.settlementMethod =
                      data.customerSettlementMethodName;
                    this.saleOrder.paymentTerm =
                      data.customerCollectionPeriodName;
                    this.saleOrder.deliveryAddress = data.invoiceAddress;
                    this.saleOrder.customerContact =
                      data.customerContacts[0].customerContactName;
                    this.saleOrder.contactInfo = data.customerContacts[0].phone;
                    this.saleOrder.customerContactID =
                      data.customerContacts[0].customerContactId;
                    this.customerContact = {
                      customerContactId:
                        data.customerContacts[0].customerContactId,
                      customerContactName:
                        data.customerContacts[0].customerContactName,
                    };
                    this.UserService.GetUserById(data.salesmanId).subscribe(
                      (data: any) => {
                        this.saleOrder.salesman = data.name;
                        this.UserService.GetDepartmentById(
                          data.departmentId
                        ).subscribe((data: any) => {
                          this.saleOrder.department = data.name;
                        });
                      }
                    );
                  });
                } else {
                  this.CustomerService.GetCustomerById(
                    results.modalContentInstance.filterRows[0].quotation
                      .customerID
                  ).subscribe((data: any) => {
                    this.saleOrder.customerID = data.customerId;
                    this.customerLinkMan = data.customerContacts;
                    this.saleOrder.settlementMethod =
                      data.customerSettlementMethodName;
                    this.saleOrder.paymentTerm =
                      data.customerCollectionPeriodName;
                    this.saleOrder.deliveryAddress = data.invoiceAddress;
                  });
                  this.saleOrder.salesman =
                    results.modalContentInstance.filterRows[0].quotation.salesmanName;
                  this.saleOrder.department =
                    results.modalContentInstance.filterRows[0].quotation.department;
                  this.saleOrder.customerName =
                    results.modalContentInstance.filterRows[0].quotation.customerName;
                  this.saleOrder.customerShortName =
                    results.modalContentInstance.filterRows[0].quotation.customerShortName;
                  this.saleOrder.settlementCurrency =
                    results.modalContentInstance.filterRows[0].quotation.currency;
                  this.saleOrder.customerContact =
                    results.modalContentInstance.filterRows[0].quotation.customerContact;
                  this.customerContact = {
                    customerContactId:
                      results.modalContentInstance.filterRows[0].quotation
                        .customerContactID,
                    customerContactName:
                      results.modalContentInstance.filterRows[0].quotation
                        .customerContact,
                  };
                  this.saleOrder.customerContactID =
                    results.modalContentInstance.filterRows[0].quotation.customerContactID;
                  this.saleOrder.contactInfo =
                    results.modalContentInstance.filterRows[0].quotation.contactInfo;
                  this.saleOrder.remark =
                    results.modalContentInstance.filterRows[0].quotation.remark;
                }
                this.saleOrder.saleOrderParts =
                  this.saleOrder.saleOrderParts.filter(
                    (part) => part.partNum !== '' && part.partNum !== null
                  );
                const newfilterRows =
                  results.modalContentInstance.filterRows.map((item: any) => {
                    return {
                      saleOrderPartId: null, //零件ID
                      saleOrderNum: this.saleOrder.saleOrderNum, //销售订单号
                      attachment: '', //
                      partNum: item.partNum,
                      image: item.pictureUrl,
                      saleOrderPartPartId: item.quotationItemPartId,
                      partName: item.partName,
                      partType: item.partType,
                      description: item.description,
                      quantity: item.quantity - item.transQuantity,
                      partUOM: item.partUOM,
                      priceWithTax: item.priceWithTax,
                      priceWithoutTax: item.priceWithoutTax,
                      taxRate: item.taxRate,
                      discount: item.discount,
                      realTimeInventory: 0,
                      discountPriceWithTax: item.discountedPriceWithTax,
                      amountWithTax: item.amountWithTax,
                      amountWithoutTax: item.amountWithoutTax,
                      taxAmount: item.taxAmount,
                      discountAmountWithTax: item.discountedAmountWithTax,
                      discountAmountWithoutTax: item.discountedAmountWithoutTax,
                      discountTaxAmount: item.discountedTaxAmount,
                      partRemark: item.partRemark,
                      sourceQuotationNum: item.quotation.quotationNum,
                      plannedShipmentDate: this.defaultDate,
                      saleOrderId: 0,
                      quotationItemId: item.quotationItemId,
                      produceQuantity: 0,
                      soldQuantity: 0,
                      unSoldQuantity: 0,
                    };
                  });
                this.saleOrder.saleOrderParts =
                  this.saleOrder.saleOrderParts.concat(newfilterRows);
                this.saleOrder.saleOrderParts.forEach((part: any) => {
                  this.calculateAmount(part);

                  this.StorehouseService.GetPartsAllInventory([
                    part.saleOrderPartPartId,
                  ]).subscribe((res: any) => {
                    part.realTimeInventory = res[0].inventory;
                  });
                });

                this.calculateTotal();
                results.modalInstance.hide();
              } else {
                this.showToast('error', '错误', '请选择相同客户的报价单');
              }
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
